package com.fjzcit.mysqltuning.controller;

import com.fjzcit.mysqltuning.service.OOMService;
import com.fjzcit.performancetuning.entities.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Author Atu
 * @Date 2024/6/23
 * @Version 1.0
 * 模拟 JVM 堆内存溢出的控制器
 */
@RestController
@Slf4j
@RequestMapping(value = "/oom")
public class OOMController {
	
	@Resource
	private OOMService oomService;
	
	/**
	 * 触发堆内存溢出
	 * @return 操作结果
	 */
	@GetMapping(value = "/trigger")
	public CommonResult<String> triggerOOM() {
		log.info("收到触发堆内存溢出请求");
		
		try {
			String result = oomService.triggerOOM();
			// 检查返回结果是否包含错误信息
			if (result.contains("堆内存溢出已触发") || result.contains("OOM")) {
				return new CommonResult<>(507, "堆内存溢出触发成功", result);
			}
			return new CommonResult<>(200, "操作完成", result);
		} catch (OutOfMemoryError e) {
			log.error("触发堆内存溢出时发生 OOM: {}", e.getMessage(), e);
			return new CommonResult<>(507, "触发堆内存溢出时发生 OOM: " + e.getMessage(), null);
		} catch (Exception e) {
			log.error("触发堆内存溢出时发生异常: {}", e.getMessage(), e);
			return new CommonResult<>(500, "触发堆内存溢出时发生异常: " + e.getMessage(), null);
		}
	}
	
	/**
	 * 申请指定大小的内存
	 * @param sizeMB 要申请的内存大小（MB）
	 * @return 申请结果
	 */
	@GetMapping(value = "/allocate/{sizeMB}")
	public CommonResult<String> allocateMemory(@PathVariable int sizeMB) {
		log.info("收到申请 {} MB 内存请求", sizeMB);
		try {
			String result = oomService.allocateMemory(sizeMB);
			// 检查返回结果是否包含错误信息
			if (result.contains("申请内存失败") || result.contains("OOM")) {
				return new CommonResult<>(507, "申请 " + sizeMB + " MB 内存失败", result);
			}
			return new CommonResult<>(200, "申请 " + sizeMB + " MB 内存成功", result);
		} catch (OutOfMemoryError e) {
			log.error("申请 {} MB 内存失败，发生 OOM: {}", sizeMB, e.getMessage(), e);
			return new CommonResult<>(507, "申请 " + sizeMB + " MB 内存失败，发生 OOM: " + e.getMessage(), null);
		} catch (Exception e) {
			log.error("申请 {} MB 内存时发生异常: {}", sizeMB, e.getMessage(), e);
			return new CommonResult<>(500, "申请 " + sizeMB + " MB 内存时发生异常: " + e.getMessage(), null);
		}
	}
}